package com.hxzy.system.feign;

import cn.hutool.json.JSONUtil;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.system.dto.AdminLoginDTO;
import com.hxzy.system.entity.SysDictData;
import com.hxzy.system.entity.SysOperLog;
import com.hxzy.system.vo.SysUserVO;
import feign.hystrix.FallbackFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Log4j2
@Component
public class SystemServiceFeignClientFallbackFactory implements FallbackFactory<SystemServiceFeignClient> {
    @Override
    public SystemServiceFeignClient create(Throwable cause) {
        return new SystemServiceFeignClientImpl(cause);
    }

    /**
     * 内部类重新实现服务降级的功能
     */
    class SystemServiceFeignClientImpl implements SystemServiceFeignClient{

        private Throwable cause;

        public SystemServiceFeignClientImpl(Throwable cause){
            this.cause=cause;
        }

        @Override
        public R<List<SysDictData>> findAllDictData() {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R<List<SysDictData>> findByDictTypeByDataBase(String dictType) {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R<List<SysDictData>> findByDictTypeByRedis(String dictType) {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R addLog(SysOperLog sysOperLog) {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R<SysUserVO> findUserByName(String username) {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R<Set<String>> findUserOwnPerm(Long userId) {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R authentication(@Valid AdminLoginDTO adminLoginDTO) {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R userInfo() {
            return convertToR(this.cause.getMessage());
        }

        @Override
        public R getRouters() {
            return convertToR(this.cause.getMessage());
        }

    }


    /**
     * 判断是不是json
     * @return
     */
    private R convertToR(String json){
        try{
           R r= JSONUtil.toBean(json,R.class);
           return r;
        }catch (Exception e){
            return R.build(AckCode.FAIL);
        }
    }

}
